#include <algorithm>
#include "User.h"
#include "TestService.h"

void TestService::AddUser(User *user)
{
	user->thread = this;
	for(int i = 0;i < ADD_LIST_SIZE;++i)
	{
		if(mutex[i].TryLock())
		{
			add_user_list[i].push_back(user);
			mutex[i].UnLock();
			return ;
		}
	}

	printf("2 time add fail\n");
	
}

void TestService::AddAllUser(User *user)
{
	for(int i = 0;i < ADD_LIST_SIZE;++i)
	{
		if(all_mutex[i].TryLock())
		{
			add_all_user_list[i].push_back(user);
			all_mutex[i].UnLock();
			return ;
		}
	}

	printf("2 time add fail\n");
	
}

bool TestService::Update()
{

	for(int i = 0;i < ADD_LIST_SIZE;++i)
	{
		if(mutex[i].TryLock())
		{
			for(int j = 0;j < add_user_list[i].size();++j)
				user_list.push_back(add_user_list[i][j]);
			add_user_list[i].clear();
			mutex[i].UnLock();
		}
	}

	for(int i = 0;i < ADD_LIST_SIZE;++i)
	{
		if(all_mutex[i].TryLock())
		{
			for(int j = 0;j < add_all_user_list[i].size();++j)
				all_user_list.push_back(add_all_user_list[i][j]);
			add_all_user_list[i].clear();
			all_mutex[i].UnLock();
		}
	}

	char test[13] = { 0 };
	for (vector<User*>::iterator iter = user_list.begin();iter != user_list.end();)
	{
		if((*iter)->socket->last_ping_time + 50 < cur_time)
			(*iter)->socket->Disconnect();		

		if((*iter)->socket->Disconnected())
		{
			(*iter)->socket->Release();
			iter = user_list.erase(iter);
			continue;
		}

		while ((*iter)->read_stream->Read(test, 11))
		{
			if (strcmp(test, "12345678901"))
				printf("%s \n", test);
			(*iter)->socket->last_ping_time = cur_time;	
			char a[] = "12345678901";			
			//(*iter)->write_stream->Write(a, 11);
			for_each(all_user_list.begin(),all_user_list.end(),
			[this,&a](User *user){
				this->AddEvent(user->thread,user,&User::Send,String(a),11);			
			});
			memset(test, 0, 13);
		}
		//for(int i = 0;i < 12;++i)
		//{	
		//	char a[] = "12345678901";			
		//	(*iter)->write_stream->Write(a, 11);
		//}
		++iter;
	}
	for (vector<User*>::iterator iter = all_user_list.begin(), iter_end = all_user_list.end(); iter != iter_end;)
	{	
		if((*iter)->socket->Disconnected())
		{
			iter = all_user_list.erase(iter);
			iter_end = all_user_list.end();
			continue;
		}
		++iter;
	}

	for (vector<User*>::iterator iter = user_list.begin(), iter_end = user_list.end(); iter != iter_end; ++iter)
	{
		(*iter)->socket->Send();
	}	
	return true;

}
